<?php
/**
 * Created by PhpStorm
 * User: ZhuYunlong2018
 * Email: 920200256@qq.com
 * Date: 2021/11/2
 * Time: 9:52
 */

namespace app\admin\validate\article;


use app\common\model\article\Article;
use app\common\validate\BaseValidate;

class ArticleValidate extends BaseValidate
{
    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'id' => 'require|number',
        'title' => 'require|nameRepeat|max:64',
        'content_short' => 'require|max:256',
        'category_id' => 'require|number|isPositiveInteger',
        'content' => 'require',
        'status' => 'require',
    ];


    /**
     * 定义错误信息
     * 格式：'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [
        'title.require' => '名称为必填项',
        'title.max' => '名称最多不能超过32个字符',
    ];

    protected $scene = [
        'create' => [
            'title',
            'category_id',
            'content',
            'content_short',
            'status'
        ],

        'update' => [
            'id',
            'title',
            'category_id',
            'content_short',
            'content',
            'status'
        ],
        'delete' => [
            'id'
        ]
    ];

    /**
     * 名称不能重复
     * @param $value
     * @param string $rule
     * @param string $data
     * @param string $field
     * @return bool|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function nameRepeat($value, $rule = '', $data = '', $field = '')
    {
        if (empty($value)) {
            return $field . '不允许为空';
        }
        $check = Article::when(isset($data['id']), function ($query) use ($data) {
            $query->where('id', '<>', $data['id']);
        })
            ->where('title', '=', $value)
            ->find();
        if ($check !== null) {
            return $field . '已存在';
        }
        return true;
    }
}